<?php

namespace app\controller\api;

use app\repository\UserRepository;
use app\request\UserRequest;
use catcher\CatchAuth;
use catcher\CatchResponse;
use catcher\exceptions\FailedException;
use catcher\library\WeChat;
use think\facade\Cache;

class Auth
{
    protected $repository;
    public function __construct(UserRepository $repository)
    {
        $this->repository = $repository;
    }

    /**
     * 测试接口
     */
    public function test()
    {
        return CatchResponse::success(['desc' => '测试接口']);
    }

    /**
     * 小程序 获取登录凭证
     */
    public function wxLogin(string $code)
    {
        $result = WeChat::miniProgram()->auth->session($code);
        if (isset($result['openid']) && isset($result['session_key'])) {
            Cache::store('redis')->set('session_key:' . $result['openid'], $result['session_key'], 604800);
            return CatchResponse::success(['openid' => $result['openid']]);
        }
        return CatchResponse::fail($result['errmsg']);
    }

    /**
     * 消息解密（比如获取电话等功能，信息是加密的，需要解密）
     */
    protected function decrypt(array $params)
    {
        $sessionKey = Cache::store('redis')->get('session_key:' . $params['openid']);
        if (!$sessionKey) return CatchResponse::fail('登录凭证已失效或不存在');

        try {
            return WeChat::miniProgram()->encryptor->decryptData($sessionKey, $params['iv'], $params['encryptedData']);
        } catch (FailedException $e) {
            return CatchResponse::fail('系统开了小差！您可以重新尝试一次哦');
        }
    }

    /**
     * 获取微信用户信息
     */
    public function wxGetUserInfo(UserRequest $request)
    {
        $params = $request->post();
        $userInfo = $this->decrypt($params);
        return CatchResponse::success($this->repository->afterWxGetUserInfo($params['openid'], $userInfo));
    }

    /**
     * 获取微信绑定的手机号
     */
    public function wxGetPhoneNumber(UserRequest $request, CatchAuth $auth)
    {
        $params = $request->post();
        $result = $this->decrypt($params);
        return CatchResponse::success($this->repository->afterwxGetPhoneNumber($params['openid'], $result['purePhoneNumber'], $auth));
    }
}
